package com.hong.utils.condition;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: Administrator
 * @Date: 2018/7/23 16:44
 * @Description:
 */
public class ConditionExample2 {


    private final static ReentrantLock lock = new ReentrantLock(true    );

    private final static Condition condition = lock.newCondition();

    private static int data = 0;

    private static volatile boolean noUse = true;

    /**
     * 1.not use the Condition only use the lock?
     * 2.the produ
     * @param args
     */
    public static void main(String[] args) {
        new Thread(()->{
            for (;;){
                buildData();
            }
        }).start();

        new Thread(()->{
            for (;;){
                useData();
            }

        }).start();
    }

    private static  void buildData() {
        try {
            //synchronized key word
            lock.lock();
           /* while (noUse){
                *//*monitor.wait();*//*
                condition.await();
            }*/
            data++;
            Optional.of("P:"+data).ifPresent(System.out::println);
            TimeUnit.SECONDS.sleep(1);
            /*noUse = true;
            *//*monitor motify*//*
            condition.signalAll();*/
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            /*synchronized end #monitor end*/
            lock.unlock();
        }
    }

    private static void useData(){
        try {
            lock.lock();
           /* while (!noUse){
                condition.await();
            }*/
            /*TimeUnit.SECONDS.sleep(1);*/
            Optional.of("C:"+data).ifPresent(System.out::println);
           /* noUse=false;

            condition.signalAll();*/
        } finally {
            lock.unlock();
        }
    }



}
